<template>
  <el-upload
    :multiple="this.multiple"
    :show-file-list="true"
    :file-list="fileList"
    :list-type="this.list_type"
    :before-upload="beforeUpload"
    :http-request="upload"
    :on-remove="handleRemove"
    class="upload-demo"
    action=""
    drag
  >
    <i class="el-icon-upload" />
    <div class="el-upload__text">
      将文件拖到此处，或<em>点击上传</em>
    </div>
  </el-upload>
</template>

<script>
import { fileUpload } from '@/api/tools/upload'
export default {
  props: {
    file_type: {
      type: String,
      default: ''
    },
    file_size: {
      type: Number,
      default: 5
    },
    multiple: {
      type: Boolean,
      default: false
    },
    list_type: {
      type: String,
      default: 'text'
    },
    value: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  watch: {
    value: function(val) {
      this.reFileList(val)
    }
  },
  mounted() {
    this.reFileList(this.value)
  },
  methods: {
    reFileList(val) {
      if (val.url === undefined || val.url === '') {
        this.fileList = []
      } else {
        this.fileList = [{ name: val.fileName, url: val.url }]
      }
    },
    handleRemove(file, fileList) {
      this.value.fileName = undefined
      this.value.serverFileName = undefined
      this.value.url = undefined
      this.emitInput(this.value)
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    beforeUpload(file) {
      // 判断文件大小
      if ((file.size / 1024 / 1024) > this.file_size) {
        this.$message.error('上传文件大小不能超过 ' + this.file_size + 'MB!')
        return false
      }

      // 判断文件格式
      if (this.file_type.trim() === '') {
        return true
      }
      const typeList = this.file_type.split('|')
      for (let i = 0; i < typeList.length; i++) {
        if ((typeList[i].trim() !== '') && (file.name.toLowerCase().endsWith(typeList[i]))) {
          return true
        }
      }
      this.$message.error('只能上传如下格式文件：' + this.file_type)
      return false
    },
    upload(content) {
      const tempData = new FormData()
      tempData.append('file', content.file)
      tempData.append('type', 'keepFiles')
      fileUpload(tempData).then((response) => {
        this.fileList = [{ name: response.data.fileName, url: response.data.url }]
        this.value.fileName = response.data.fileName
        this.value.serverFileName = response.data.serverFileName
        this.value.url = response.data.url
        this.emitInput(this.value)
      })
    }
  }
}
</script>
